
from flask import Flask, render_template, request, jsonify, send_file, session, redirect, url_for
from flask_cors import CORS
import os
import sys
import json
from datetime import datetime
from pathlib import Path
import tempfile


sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'code'))

from database import Database, init_db
from translation_service import TranslationService
from auth_database import AuthDatabase, init_auth_db
from auth_utils import login_required, admin_required, get_current_user, set_user_session, clear_user_session
from auth_routes import register_auth_routes


app = Flask(__name__)
app.config['SECRET_KEY'] = 'french-teacher-secret-key-2025-change-this-in-production'
app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024
app.config['PERMANENT_SESSION_LIFETIME'] = 86400
CORS(app, supports_credentials=True)


db = Database()
auth_db = AuthDatabase()


translation_service = TranslationService()


TEMP_DIR = Path(tempfile.gettempdir()) / 'french_teacher_temp'
TEMP_DIR.mkdir(exist_ok=True)




@app.route('/login')
def login():

    if 'user_id' in session:
        return redirect(url_for('index'))
    return render_template('login.html')


@app.route('/register')
def register():

    if 'user_id' in session:
        return redirect(url_for('index'))
    return render_template('register.html')




@app.route('/')
@login_required
def index():
    user = get_current_user()
    return render_template('index.html', user=user)


@app.route('/vocabulary')
@login_required
def vocabulary():
    user = get_current_user()
    return render_template('vocabulary.html', user=user)


@app.route('/admin')
@admin_required
def admin_panel():
    user = get_current_user()
    return render_template('admin.html', user=user)


@app.route('/history')
@login_required
def history():
    user = get_current_user()
    return render_template('history.html', user=user)


@app.route('/credits')
def credits():
    return render_template('credits.html')




@app.route('/api/translate', methods=['POST'])
@login_required
def translate_audio():
    try:

        user = get_current_user()


        has_limit, message = auth_db.check_token_limit(user['id'])
        if has_limit:
            return jsonify({
                'error': f'Token额度不足: {message}',
                'success': False
            }), 403

        if 'audio' not in request.files:
            return jsonify({'error': '未收到音频文件'}), 400

        audio_file = request.files['audio']
        direction = request.form.get('direction', 'fr2zh')
        mode = int(request.form.get('mode', 1))


        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        temp_audio_path = TEMP_DIR / f'recording_{timestamp}.wav'
        audio_file.save(str(temp_audio_path))

        print(f"📥 收到音频: {temp_audio_path.name}")
        print(f"   方向: {direction}")
        print(f"   模式: {mode}")


        result = translation_service.process_audio(
            audio_path=str(temp_audio_path),
            direction=direction,
            mode=mode
        )


        auth_db.record_token_usage(
            user['id'],
            xunfei_tokens=result['usage']['xunfei_chars'],
            qwen_tokens=result['usage']['qwen_tokens']
        )


        auth_db.add_translation_history(
            user_id=user['id'],
            original_text=result['original_text'],
            translated_text=result['translated_text'],
            polished_text=result['polished_text'],
            direction=direction,
            xunfei_usage=result['usage']['xunfei_chars'],
            qwen_usage=result['usage']['qwen_tokens']
        )





        return jsonify({
            'success': True,
            'data': result
        })

    except Exception as e:
        print(f"❌ 翻译错误: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({
            'error': str(e),
            'success': False
        }), 500


@app.route('/api/vocabulary', methods=['GET'])
@login_required
def get_vocabulary():
    try:
        user = get_current_user()
        words = db.get_user_words(user['id'])
        return jsonify({
            'success': True,
            'data': words
        })
    except Exception as e:
        return jsonify({
            'error': str(e),
            'success': False
        }), 500


@app.route('/api/vocabulary', methods=['POST'])
@login_required
def add_vocabulary():
    try:
        user = get_current_user()
        data = request.get_json()

        if not data or 'french' not in data or 'chinese' not in data:
            return jsonify({'error': '缺少必要字段'}), 400


        audio_url = None
        if data.get('generate_audio', False):

            from datetime import datetime
            from tts_module import text_to_speech

            timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
            audio_name = f'vocab_{timestamp}.mp3'
            audio_dir = Path(__file__).parent.parent / '数据' / '单词本音频'
            audio_dir.mkdir(parents=True, exist_ok=True)
            audio_path = audio_dir / audio_name

            try:
                tts_success, tts_usage = text_to_speech(
                    text=data['french'],
                    output_path=str(audio_path),
                    language='french'
                )
                if tts_success:
                    audio_url = f'/api/audio/vocab/{audio_name}'
            except:
                pass

        word_id = db.add_word(
            user_id=user['id'],
            french=data['french'],
            chinese=data['chinese'],
            category=data.get('category', '翻译结果'),
            audio_url=audio_url
        )

        return jsonify({
            'success': True,
            'message': '添加成功',
            'id': word_id,
            'audio_url': audio_url
        })

    except Exception as e:
        return jsonify({
            'error': str(e),
            'success': False
        }), 500


@app.route('/api/vocabulary/<int:word_id>/generate-audio', methods=['POST'])
@login_required
def generate_vocab_audio(word_id):
    try:
        from tts_module import text_to_speech


        word = db.get_word(word_id)
        if not word:
            return jsonify({'error': '单词不存在'}), 404


        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        audio_name = f'vocab_{timestamp}.mp3'
        audio_dir = Path(__file__).parent.parent / '数据' / '单词本音频'
        audio_dir.mkdir(parents=True, exist_ok=True)
        audio_path = audio_dir / audio_name

        tts_success, tts_usage = text_to_speech(
            text=word['french'],
            output_path=str(audio_path),
            language='french'
        )

        if tts_success:
            audio_url = f'/api/audio/vocab/{audio_name}'


            db.update_word(word_id, audio_url=audio_url)

            return jsonify({
                'success': True,
                'message': '音频生成成功',
                'audio_url': audio_url
            })
        else:
            return jsonify({
                'error': '音频生成失败',
                'success': False
            }), 500

    except Exception as e:
        return jsonify({
            'error': str(e),
            'success': False
        }), 500


@app.route('/api/vocabulary/<int:word_id>', methods=['DELETE'])
@login_required
def delete_vocabulary(word_id):
    try:
        db.delete_word(word_id)
        return jsonify({
            'success': True,
            'message': '删除成功'
        })
    except Exception as e:
        return jsonify({
            'error': str(e),
            'success': False
        }), 500


@app.route('/api/vocabulary/<int:word_id>', methods=['PUT'])
def update_vocabulary(word_id):
    try:
        data = request.get_json()

        db.update_word(
            word_id=word_id,
            french=data.get('french'),
            chinese=data.get('chinese'),
            category=data.get('category')
        )

        return jsonify({
            'success': True,
            'message': '更新成功'
        })

    except Exception as e:
        return jsonify({
            'error': str(e),
            'success': False
        }), 500


@app.route('/api/vocabulary/search', methods=['GET'])
@login_required
def search_vocabulary():
    try:
        user = get_current_user()
        keyword = request.args.get('q', '')
        words = db.search_words(keyword, user_id=user['id'])

        return jsonify({
            'success': True,
            'data': words
        })

    except Exception as e:
        return jsonify({
            'error': str(e),
            'success': False
        }), 500


@app.route('/api/vocabulary/export', methods=['GET'])
def export_vocabulary():
    try:
        words = db.get_all_words()


        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        export_path = TEMP_DIR / f'vocabulary_export_{timestamp}.json'

        with open(export_path, 'w', encoding='utf-8') as f:
            json.dump(words, f, ensure_ascii=False, indent=2)

        return send_file(
            export_path,
            as_attachment=True,
            download_name=f'vocabulary_{timestamp}.json',
            mimetype='application/json'
        )

    except Exception as e:
        return jsonify({
            'error': str(e),
            'success': False
        }), 500


@app.route('/api/stats', methods=['GET'])
@login_required
def get_stats():
    try:
        user = get_current_user()
        stats = db.get_statistics(user_id=user['id'])
        return jsonify({
            'success': True,
            'data': stats
        })
    except Exception as e:
        return jsonify({
            'error': str(e),
            'success': False
        }), 500


@app.route('/api/audio/<path:filename>', methods=['GET'])
def get_audio(filename):
    try:

        audio_dir = Path(__file__).parent.parent / '数据' / '翻译结果'
        audio_path = audio_dir / filename

        if not audio_path.exists():
            return jsonify({'error': '音频文件不存在'}), 404

        return send_file(
            audio_path,
            mimetype='audio/mpeg',
            as_attachment=False
        )
    except Exception as e:
        return jsonify({
            'error': str(e),
            'success': False
        }), 500


@app.route('/api/audio/vocab/<path:filename>', methods=['GET'])
def get_vocab_audio(filename):
    try:
        audio_dir = Path(__file__).parent.parent / '数据' / '单词本音频'
        audio_path = audio_dir / filename

        if not audio_path.exists():
            return jsonify({'error': '音频文件不存在'}), 404

        return send_file(
            audio_path,
            mimetype='audio/mpeg',
            as_attachment=False
        )
    except Exception as e:
        return jsonify({
            'error': str(e),
            'success': False
        }), 500




@app.errorhandler(404)
def not_found(e):
    return jsonify({'error': '页面未找到'}), 404


@app.errorhandler(500)
def internal_error(e):
    return jsonify({'error': '服务器内部错误'}), 500




if __name__ == '__main__':
    print("="*70)
    print("🚀 法语学习系统 Web 服务器 (多用户版)")
    print("="*70)
    print()
    print("📊 初始化数据库...")
    init_db()
    init_auth_db()
    print("✓ 数据库初始化完成")
    print()
    print("🔐 注册认证路由...")
    register_auth_routes(app)
    print("✓ 认证路由注册完成")
    print()
    print("🌐 服务器地址:")
    print("   本地访问: http://127.0.0.1:5001")
    print("   局域网访问: http://0.0.0.0:5001")
    print()
    print("📄 可用页面:")
    print("   登录页面: http://127.0.0.1:5001/login")
    print("   注册页面: http://127.0.0.1:5001/register")
    print("   主页（录音翻译）: http://127.0.0.1:5001/")
    print("   单词本: http://127.0.0.1:5001/vocabulary")
    print("   管理员面板: http://127.0.0.1:5001/admin")
    print()
    print("👤 默认管理员账号:")
    print("   用户名: Mike.Chen")
    print("   密码: Chen@123")
    print("   ⚠️  首次登录后请修改密码！")
    print()
    print("⚠️  按 Ctrl+C 停止服务器")
    print("="*70)
    print()

    app.run(
        host='0.0.0.0',
        port=5001,
        debug=True
    )
